package com.base.springboot.starter.mybatisplus.util;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.*;

/**
 * MybatisPlus 代码生成器
 *
 * @author admin
 * @date 2020/5/8 AM11:10
 */
@Slf4j
public class MybatisPlusCodeGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        log.info(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     *
     * @param modelNameTmp
     * @param packagePath
     * @param dataSourceConfig
     * @param args
     * @throws Exception
     */
    public static void autoGenerator(String modelNameTmp, String packagePath, DataSourceConfig dataSourceConfig, String[] args) throws Exception {
        String modelDirPath = packagePath.replaceAll("\\.", "/");

        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        globalConfig.setOutputDir(projectPath);
        globalConfig.setAuthor(System.getProperty("user.name"));
        globalConfig.setOpen(false);
        globalConfig.setSwagger2(true);
        //是否覆盖
        globalConfig.setFileOverride(false);
        // 不需要ActiveRecord特性的请改为false
        globalConfig.setActiveRecord(true);
        // XML 二级缓存
        globalConfig.setEnableCache(false);
        // XML ResultMap
        globalConfig.setBaseResultMap(true);
        // XML columList
        globalConfig.setBaseColumnList(true);
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据源配置
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        autoGenerator.setDataSource(dataSourceConfig);

        // 包名策略配置
        PackageConfig packageConfig = new PackageConfig();
        String scannerFirst = scanner("模块名");

        packageConfig.setModuleName(scannerFirst);
        packageConfig.setParent(packagePath);
        packageConfig.setMapper("mapper");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setEntity("entity");
        autoGenerator.setPackageInfo(packageConfig);

        // 自定义配置
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                // not to do
            }
        };

        // 如果模板引擎是 freemarker
        String xmlTemplatePath = "/templates/mapper.xml.ftl";
        String entityTemplatePath = "/templates/entity.java.ftl";
        String mapperTemplatePath = "/templates/mapper.java.ftl";
        String serviceTemplatePath = "/templates/service.java.ftl";
        String serviceImplTemplatePath = "/templates/serviceImpl.java.ftl";
        String controllerTemplatePath = "/templates/controller.java.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        //entity
        focList.add(new FileOutConfig(entityTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-entity/src/main/java/" + modelDirPath + "/entity/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });
        //mapper xml
        focList.add(new FileOutConfig(xmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/" + modelNameTmp + "-admin/src/main/resources/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        focList.add(new FileOutConfig(xmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/" + modelNameTmp + "-service/src/main/resources/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        //mapper java
        focList.add(new FileOutConfig(mapperTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-admin/src/main/java/" + modelDirPath + "/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getMapperName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(mapperTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-service/src/main/java/" + modelDirPath + "/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getMapperName() + StringPool.DOT_JAVA;
            }
        });
        //service
        focList.add(new FileOutConfig(serviceTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-admin/src/main/java/" + modelDirPath + "/service/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(serviceTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-service/src/main/java/" + modelDirPath + "/service/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
            }
        });
        //service impl
        focList.add(new FileOutConfig(serviceImplTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-admin/src/main/java/" + modelDirPath + "/service/" + packageConfig.getModuleName() + "/impl"
                        + "/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig(serviceImplTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-service/src/main/java/" + modelDirPath + "/service/" + packageConfig.getModuleName() + "/impl"
                        + "/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
            }
        });
        //controller impl
        focList.add(new FileOutConfig(controllerTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-admin/src/main/java/" + modelDirPath + "/controller/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig(controllerTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/" + modelNameTmp + "-service/src/main/java/" + modelDirPath + "/controller/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
            }
        });
        injectionConfig.setFileOutConfigList(focList);
        autoGenerator.setCfg(injectionConfig);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        autoGenerator.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //是否大写命名 默认false
        strategy.setCapitalMode(true);
        //过滤表的前缀
        strategy.setTablePrefix("t_");
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setLogicDeleteFieldName("del_flag");

        strategy.setSuperServiceImplClass("com.base.springboot.starter.mybatisplus.service.GenericServiceImpl");
        strategy.setSuperServiceClass("com.base.springboot.starter.mybatisplus.service.GenericService");
//        strategy.setSuperEntityClass("com.base.springboot.starter.mybatisplus.domain.GenericBaseEntity");
        //自动lombok
        strategy.setEntityLombokModel(true);
        strategy.setEntitySerialVersionUID(true);
        strategy.setEntityColumnConstant(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        TableFill insertDate = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateDate = new TableFill("modify_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(insertDate);
        tableFills.add(updateDate);
        strategy.setTableFillList(tableFills);
        strategy.setRestControllerStyle(true);

        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        autoGenerator.setStrategy(strategy);
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());

        //自定义文件生成路径，包路径
        //这里调用customPackagePath方法，使用可以自己在内部灵活配置路径
        //如果不调用该方法、就会使用MyBatis-Plus默认的文件生成路径和包路径生成文件、但可以使用上面的PackageConfig做一些简单的配置
        customPackagePath(packagePath, packageConfig, autoGenerator);

        autoGenerator.execute();
    }

    /**
     *
     * @param packagePath
     * @param packageConfig
     * @param autoGenerator
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void customPackagePath(String packagePath, PackageConfig packageConfig, AutoGenerator autoGenerator) throws NoSuchFieldException, IllegalAccessException {
        String moduleName = packageConfig.getModuleName();

        /**
         * packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径
         * 这里包路径可以根据实际情况灵活配置
         */
        Map<String, String> packageInfo = new HashMap<>();
        packageInfo.put(ConstVal.CONTROLLER, packagePath + ".controller." + moduleName );
        packageInfo.put(ConstVal.SERVICE, packagePath + ".service." + moduleName);
        packageInfo.put(ConstVal.SERVICE_IMPL, packagePath + ".service." + moduleName + ".impl");
        packageInfo.put(ConstVal.ENTITY, packagePath + ".entity." + moduleName);
        packageInfo.put(ConstVal.MAPPER, packagePath + ".mapper." + moduleName);

        /**
         * 创建configBuilder对象，传入必要的参数
         *
         * 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上
         * 因为packageInfo是私有成员变量，也没有提交提供公共的方法，所以使用反射注入
         * 为啥要这么干，看源码去吧
         */
        ConfigBuilder configBuilder = new ConfigBuilder(autoGenerator.getPackageInfo(), autoGenerator.getDataSource(), autoGenerator.getStrategy(), autoGenerator.getTemplate(), autoGenerator.getGlobalConfig());
        Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
        packageInfoField.setAccessible(true);
        packageInfoField.set(configBuilder, packageInfo);

        /**
         * 设置配置对象
         */
        autoGenerator.setConfig(configBuilder);
    }
}